<template>
  <div class="common-layout">
    <div v-if="isMobile && !isMenuCollapsed" class="mobile-overlay" @click="toggleMenu">
    </div>
    <el-container>
      <el-header class="header">
        <div class="header-content">
          <div class="menu-toggle" @click="toggleMenu">
            <el-icon>
              <Expand v-if="isMenuCollapsed" />
              <Fold v-else />
            </el-icon>
          </div>
          <div class="user-info">
            <span>欢迎， {{ userName }} </span>
            <el-button type="danger" size="small" @click="logout" style="margin-left: 10px;">退出</el-button>
          </div>
        </div>
      </el-header>
      <el-container class="main-container">
        <el-aside :width="isMenuCollapsed ? '64px' : '240px'" class="aside"
          :class="{ 'mobile-aside': isMobile, 'collapsed': isMenuCollapsed }">
          <el-menu :default-active="$route.path" class="el-menu-vertical-demo" :collapse="isMenuCollapsed"
            :collapse-transition="false" router>
            <el-menu-item @click="goToHomePage">
              <el-icon>
                <HomeFilled />
              </el-icon>
              <span>前台首页</span>
            </el-menu-item>
            <el-menu-item index="/study-system/profile">
              <el-icon>
                <User />
              </el-icon>
              <span>个人中心</span>
            </el-menu-item>
            <el-menu-item index="/study-system/user-management">
              <el-icon>
                <Document />
              </el-icon>
              <span>用户管理</span>
            </el-menu-item>
            <el-sub-menu index="question-bank">
              <template #title>
                <el-icon>
                  <IconMenu />
                </el-icon>
                <span>题库管理</span>
              </template>
              <el-menu-item index="/study-system/manual-import">
                <span>导入题目</span>
              </el-menu-item>
              <el-menu-item index="/study-system/question-bank/politics">时政题目</el-menu-item>
              <el-menu-item index="/study-system/question-bank/common-sense">常识题目</el-menu-item>
              <el-menu-item index="/study-system/question-bank/language">言语题目</el-menu-item>
              <el-menu-item index="/study-system/question-bank/quantity">数量题目</el-menu-item>
              <el-menu-item index="/study-system/question-bank/judgment">判断题目</el-menu-item>
              <el-menu-item index="/study-system/question-bank/data-analysis">资料题目</el-menu-item>
              <el-menu-item index="/study-system/question-bank/shenlun">申论题目</el-menu-item>
            </el-sub-menu>
            <el-menu-item index="/study-system/error-analysis">
              <el-icon>
                <Setting />
              </el-icon>
              <span>错题管理</span>
            </el-menu-item>
            <el-menu-item index="/study-system/note">
              <el-icon>
                <Document />
              </el-icon>
              <span>我的笔记</span>
            </el-menu-item>
            <el-sub-menu index="daily-accumulation">
              <template #title>
                <el-icon>
                  <Collection />
                </el-icon>
                <span>日常积累</span>
              </template>
              <el-menu-item index="/study-system/daily-accumulation/common-sense">常识积累</el-menu-item>
              <el-menu-item index="/study-system/daily-accumulation/politics">时政积累</el-menu-item>
              <el-menu-item index="/study-system/daily-accumulation/writing-material">作文素材</el-menu-item>
              <el-menu-item index="/study-system/daily-accumulation/vocabulary">
                <span>词语积累</span>
              </el-menu-item>
            </el-sub-menu>
            <el-menu-item index="/study-system/oss-image-manager">
              <el-icon>
                <Picture />
              </el-icon>
              <span>图片管理</span>
            </el-menu-item>
            <!-- 添加成就管理菜单项 -->
            <el-menu-item index="/study-system/achievement-management">
              <el-icon>
                <Medal />
              </el-icon>
              <span>成就管理</span>
            </el-menu-item>
            <!-- 添加试卷管理菜单项 -->
            <el-menu-item index="/study-system/paper-management">
              <el-icon>
                <Document />
              </el-icon>
              <span>试卷管理</span>
            </el-menu-item>
            <!-- 添加试卷分值管理菜单项 -->
            <el-menu-item index="/study-system/paper-score-management">
              <el-icon>
                <DataBoard />
              </el-icon>
              <span>试卷分值管理</span>
            </el-menu-item>
          </el-menu>
        </el-aside>
        <el-main class="main-content">
          <router-view></router-view>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onBeforeUnmount, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import {
  Location,
  Document,
  Menu as IconMenu,
  Setting,
  HomeFilled,
  DataLine,
  Edit,
  DataBoard,
  User,
  Collection,
  Fold,
  Expand,
  ChatDotRound,
  Picture,
  Medal // 添加 Medal 图标
} from '@element-plus/icons-vue';
import { useUserStore } from '@/stores/user';

const router = useRouter();
const userStore = useUserStore();

// 移动端适配相关
const isMobile = ref(false);
const isMenuCollapsed = ref(false);

// 用户信息
const currentUser = computed(() => {
  // 优先从userStore获取用户信息，确保获取到最新的数据
  if (userStore.userInfo) {
    return userStore.userInfo;
  }
  // 如果userStore中没有用户信息，再尝试从localStorage获取
  const userFromStorage = localStorage.getItem('user');
  if (userFromStorage) {
    return JSON.parse(userFromStorage);
  }
  return null;
});

const userName = computed(() => {
  return currentUser.value?.username || currentUser.value?.nickname || '用户';
});

const logout = () => {
  // 清除所有登录相关数据
  localStorage.removeItem('loggedIn');
  localStorage.removeItem('token');
  localStorage.removeItem('user');
  localStorage.removeItem('userInfo');
  userStore.clearUser();
  router.push('/');
  ElMessage.success('已退出登录');
};

// 跳转到前台首页（新标签页打开）
const goToHomePage = () => {
  const url = router.resolve('/');
  window.open(url.href, '_blank');
};

// 添加：监听用户信息更新事件
const handleUserInfoUpdated = (event: CustomEvent) => {
  // 添加调试日志
  console.log('StudySystem.vue接收到用户信息更新事件:', event.detail);
  // 更新用户store中的信息
  userStore.setUserInfo(event.detail);
  console.log('StudySystem.vue已更新用户信息，新的头像URL:', event.detail?.avatar);
};

// 检测是否为移动设备
const checkIsMobile = () => {
  const mobileBreakpoint = 768;
  isMobile.value = window.innerWidth <= mobileBreakpoint;

  // 在移动端默认折叠菜单
  if (isMobile.value) {
    isMenuCollapsed.value = true;
  } else {
    isMenuCollapsed.value = false;
  }
};

// 切换菜单显示状态
const toggleMenu = () => {
  if (isMobile.value) {
    isMenuCollapsed.value = !isMenuCollapsed.value;
  } else {
    isMenuCollapsed.value = !isMenuCollapsed.value;
  }
};

const handleOpen = (key: string, keyPath: string[]) => {
  console.log(key, keyPath);
};

const handleClose = (key: string, keyPath: string[]) => {
  console.log(key, keyPath);
};

// 处理窗口大小变化
const handleResize = () => {
  checkIsMobile();
};

// 组件挂载时初始化
onMounted(() => {
  checkIsMobile();
  window.addEventListener('resize', handleResize);
  // 添加：监听用户信息更新事件
  window.addEventListener('user-info-updated', handleUserInfoUpdated as EventListener);
});

// 组件卸载前清理事件监听器
onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize);
  // 添加：移除用户信息更新事件监听器
  window.removeEventListener('user-info-updated', handleUserInfoUpdated as EventListener);
});
</script>

<style scoped>
.common-layout {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f8fafc;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1000;
}

.mobile-overlay {
  position: fixed;
  top: 60px;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 999;
  transition: opacity 0.3s ease;
}

.el-container {
  flex: 1;
  overflow: hidden;
}

.header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  padding: 0;
  box-shadow: 0 2px 20px rgba(0, 0, 0, 0.1);
  position: relative;
  z-index: 100;
  flex-shrink: 0;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  height: 100%;
}

.menu-toggle {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  cursor: pointer;
  transition: background-color 0.3s;
  flex-shrink: 0;
  background-color: rgba(255, 255, 255, 0.1);
}

.menu-toggle:hover {
  background-color: rgba(255, 255, 255, 0.2);
}

.menu-toggle:active {
  background-color: rgba(255, 255, 255, 0.3);
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
  min-width: 0;
  flex-shrink: 0;
}

.user-info span {
  font-weight: 500;
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.header::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 1px;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
}

:deep(.user-info .el-button) {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: #fff;
  border-radius: 8px;
  transition: all 0.3s ease;
}

:deep(.user-info .el-button:hover) {
  background: rgba(255, 255, 255, 0.3);
  transform: translateY(-1px);
}

.main-container {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.aside {
  background: #ffffff;
  border-right: none;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
  position: relative;
  z-index: 50;
  flex-shrink: 0;
  overflow-y: auto;
  overflow-x: hidden;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  border-radius: 0 12px 0 0;
}

.aside.collapsed {
  overflow-x: hidden;
}

.aside.mobile-aside {
  position: fixed;
  height: calc(100% - 60px);
  top: 60px;
  left: 0;
  z-index: 1000;
  box-shadow: 2px 0 15px rgba(0, 0, 0, 0.2);
  transform: translateX(0);
  transition: transform 0.3s ease;
}

.aside.mobile-aside.collapsed {
  transform: translateX(-100%);
}

.el-menu-vertical-demo {
  height: 100%;
  border-right: none;
  overflow-y: auto;
  overflow-x: hidden;
  padding: 24px 0;
}

.el-menu-vertical-demo:not(.el-menu--collapse) {
  width: 240px;
}

:deep(.el-menu-item) {
  margin: 6px 20px;
  padding: 0 20px !important;
  border-radius: 12px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  font-size: 14px;
  font-weight: 500;
  color: #333;
  height: 48px;
  line-height: 48px;
}

:deep(.el-menu-item:hover) {
  background: rgba(0, 122, 255, 0.08);
  color: #007aff;
  transform: translateX(2px);
}

:deep(.el-menu-item.is-active) {
  background: #007aff;
  color: #fff;
  font-weight: 600;
  box-shadow: 0 4px 12px rgba(0, 122, 255, 0.3);
}

:deep(.el-sub-menu .el-sub-menu__title) {
  margin: 6px 20px;
  padding: 0 16px 0 20px !important;
  border-radius: 12px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  font-size: 14px;
  font-weight: 500;
  color: #333;
  height: 48px;
  line-height: 48px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

/* 子菜单箭头样式 */
:deep(.el-sub-menu__icon-arrow) {
  margin-left: 8px;
  margin-right: 0;
  font-size: 12px;
  transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1), color 0.3s ease;
  flex-shrink: 0;
  color: #909399;
}

:deep(.el-sub-menu .el-sub-menu__title:hover) {
  background: rgba(0, 122, 255, 0.08);
  color: #007aff;
}

:deep(.el-sub-menu .el-menu-item) {
  margin: 3px 24px 3px 40px;
  padding: 0 20px !important;
  border-radius: 10px;
  height: 42px;
  line-height: 42px;
  font-size: 13px;
  color: #666;
}

/* 菜单图标样式优化 */
:deep(.el-menu-item .el-icon) {
  font-size: 18px;
  margin-right: 12px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

:deep(.el-menu-item.is-active .el-icon) {
  transform: scale(1.1);
}

:deep(.el-sub-menu__title .el-icon) {
  font-size: 18px;
  margin-right: 12px;
  flex-shrink: 0;
}

/* 子菜单标题文字容器 */
:deep(.el-sub-menu__title span) {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-right: auto;
}

/* 子菜单展开时的样式 */
:deep(.el-sub-menu.is-opened > .el-sub-menu__title) {
  background: rgba(0, 122, 255, 0.05);
  color: #007aff;
}

/* 子菜单展开时箭头颜色 */
:deep(.el-sub-menu.is-opened > .el-sub-menu__title .el-sub-menu__icon-arrow) {
  color: #007aff;
  transform: rotate(180deg);
}

/* 子菜单项激活状态 */
:deep(.el-sub-menu .el-menu-item.is-active) {
  background: rgba(0, 122, 255, 0.12);
  color: #007aff;
  font-weight: 600;
}

/* 子菜单内边距优化 */
:deep(.el-sub-menu .el-menu) {
  background-color: transparent;
  padding: 6px 0;
}

/* 增加菜单项之间的视觉分隔 */
:deep(.el-sub-menu) {
  margin-bottom: 4px;
}

/* 移动端菜单样式优化 */
:deep(.el-menu--collapse .el-menu-item) {
  padding: 0 !important;
  margin: 6px 8px;
  border-radius: 12px;
  justify-content: center;
}

:deep(.el-menu--collapse .el-sub-menu__title) {
  padding: 0 !important;
  justify-content: center;
}

/* 折叠状态下隐藏箭头 */
:deep(.el-menu--collapse .el-sub-menu__icon-arrow) {
  display: none;
}

:deep(.el-menu--collapse .el-menu-item .el-icon) {
  margin: 0 auto;
}

:deep(.el-menu--collapse .el-menu-item span) {
  height: 0;
  width: 0;
  overflow: hidden;
  visibility: hidden;
  display: inline-block;
}

:deep(.el-menu--collapse .el-sub-menu .el-sub-menu__icon-arrow) {
  display: none;
}

.main-content {
  background: #f8fafc;
  padding: 24px;
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  transition: margin-left 0.3s ease;
}

.main-content.mobile-content {
  margin-left: 0;
}

/* 滚动条样式 */
.main-content::-webkit-scrollbar {
  width: 8px;
}

.main-content::-webkit-scrollbar-track {
  background: #f5f5f7;
  border-radius: 4px;
}

.main-content::-webkit-scrollbar-thumb {
  background: #d1d1d6;
  border-radius: 4px;
  transition: background 0.3s;
}

.main-content::-webkit-scrollbar-thumb:hover {
  background: #a1a1a6;
}

/* 侧边栏滚动条样式 */
.aside::-webkit-scrollbar {
  width: 6px;
}

.aside::-webkit-scrollbar-track {
  background: transparent;
  border-radius: 3px;
}

.aside::-webkit-scrollbar-thumb {
  background: rgba(0, 0, 0, 0.1);
  border-radius: 3px;
  transition: background 0.3s;
}

.aside::-webkit-scrollbar-thumb:hover {
  background: rgba(0, 0, 0, 0.2);
}

/* 移动端优化 */
@media screen and (max-width: 768px) {
  .header-content {
    padding: 0 10px;
  }

  .user-info span {
    font-size: 12px;
  }

  :deep(.user-info .el-button) {
    padding: 8px 12px;
    font-size: 12px;
  }

  .main-content {
    padding: 16px 12px;
  }

  :deep(.el-menu-item) {
    margin: 4px 12px;
    padding: 0 12px !important;
    height: 44px;
    line-height: 44px;
  }

  :deep(.el-sub-menu .el-sub-menu__title) {
    margin: 4px 12px;
    padding: 0 12px !important;
    height: 44px;
    line-height: 44px;
  }

  :deep(.el-sub-menu .el-menu-item) {
    margin: 3px 16px 3px 24px;
    padding: 0 12px !important;
    height: 40px;
    line-height: 40px;
  }
}

@media screen and (max-width: 480px) {
  .header-content {
    padding: 0 5px;
  }

  .user-info {
    gap: 5px;
  }

  .main-content {
    padding: 12px 8px;
  }
}
</style>
